<?php
// +----------------------------------------------------------------------
// | 麦沃德科技赋能开发者，助力中小企业发展
// +----------------------------------------------------------------------
// | Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
// +----------------------------------------------------------------------
// | Wdadmin系统产品软件并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
// +----------------------------------------------------------------------
// | Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
// +----------------------------------------------------------------------
namespace app\api\controller\wddj;

use app\api\model\wddj\User;
use app\common\controller\Api;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use Exception;

/**
 * 抬头管理
 */
class InvoiceTitle extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = ['*'];
    protected $wechat_id = null;


    protected $model = null;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\api\model\wddj\LookUp();
        $this->wechat_id = User::getWechatId($this->auth->id);
        if (empty($this->wechat_id)) {
            $this->error('用户信息不存在');
        }
    }


    /**
     * Desc  添加抬头
     * Create on 2024/8/30 16:00
     * Create by @小趴菜
     */
    public function add()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->post();
        $result = $this->validate($param, 'app\api\validate\wddj\InvoiceTitle');
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $default_id =  $this->model->where([
            'is_default'=>1,
            'wechat_id'=>$this->wechat_id,
        ])->value('id');
        if($param['is_default'] == 1 && $default_id) {
            $this->model->where('id',$default_id)->update([
                'is_default'=>2,
            ]);
        }
        $param['wechat_id'] = $this->wechat_id;
        $param['updatetime'] = time();
        $result = false;
        Db::startTrans();
        try {
            $result = $this->model->allowField(true)->save($param);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if(false === $result){
            $this->error($this->model->getError());
        }
        $this->success('请求成功');
    }

    /**
     * Desc  编辑抬头
     * Create on 2024/8/30 16:13
     * Create by @小趴菜
     */
    public function edit()
    {
        if(!$this->request->isPost()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->post();
        $result = $this->validate($param, 'app\api\validate\wddj\InvoiceTitle');
        if (true !== $result) {
            // 验证失败 输出错误信息
            $this->error($result);
        }
        $wechat_id = User::getWechatId($this->auth->id);
        $row = $this->model->where('id',$param['id'])->where('wechat_id',$wechat_id)->find();
        if (!$row) {
            $this->error('抬头信息不存在');
        }
        if($param['is_default'] == 1) {
            $this->model->where('wechat_id',$this->wechat_id)
                ->update([
                    'is_default'=>2,
                ]);
        }
        $param['updatetime'] = time();
        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->save($param);
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if(false === $result){
            $this->error($this->model->getError());
        }
        $this->success('请求成功');
    }


    /**
     * Desc  删除抬头
     * Create on 2024/8/30 16:15
     * Create by @小趴菜
     */
    public function del()
    {
        $param = $this->request->post();
        $wechat_id = User::getWechatId($this->auth->id);
        $row = $this->model->where('id',$param['id'])->where('wechat_id',$wechat_id)->find();
        if (!$row) {
            $this->error('抬头信息不存在');
        }

        $result = false;
        Db::startTrans();
        try {
            $result = $row->allowField(true)->delete();
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if(false === $result){
            $this->error($this->model->getError());
        }
        $this->success('请求成功');
    }

    /**
     * Desc  抬头列表
     * Create on 2024/8/30 17:21
     * Create by @小趴菜
     */
    public function list()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->get();
        $page = isset($param['page']) ? $param['page'] : '';
        $limit = isset($param['limit']) ? $param['limit'] : 10;
        $where = [];
        $where['wechat_id'] = array('eq',$this->wechat_id);
        $count = $this->model->where($where)->count();
        $list = $this->model
            ->where($where)
            ->field('id,invoice_title,title_type,invoice_type,is_default,mobile')
            ->order('id desc')
            ->page($page,$limit)
            ->select();
        $this->success('请求成功',['count' => $count,'data' => $list]);
    }


    public function details(){
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $param = $this->request->get();
        $wechat_id = User::getWechatId($this->auth->id);
        $data = $this->model->where('id',$param['id'])->where('wechat_id',$wechat_id)->find();
        $this->success('请求成功',$data);
    }

    /**
     * Desc 默认抬头
     * Create on 2024/10/12 9:43
     * Create by wangyafang
     */
    public function default_invoice_title()
    {
        if(!$this->request->isGet()) {
            $this->error('请求类型错误');
        }
        $where['wechat_id'] = array('eq',$this->wechat_id);
        $data = $this->model
            ->where($where)
            ->field('id,invoice_title,title_type,invoice_type,mobile')
            ->order('is_default asc,id desc')
            ->find();

        $this->success('请求成功',$data);
    }


}
